from openpyxl import Workbook, load_workbook
import config


class AddData:
    def __init__(self, file_all, file_update):
        """change column"""
        self.file_all = file_all
        self.file_update = file_update
        self.head = []
        self.update_column_nums = config.UPDATE_COLUMN_NUMS
        self.update_bug_id = config.UPDATE_BUG_ID_COLUMN
        self.update_data_lines = config.UPDATE_DATA_LINES
        self.all_lines = config.ALL_DATA_LINES
        self.bug_id_column = config.ALL_BUG_ID_COLUMN
        self.insert_line = config.INSERT_LINES

    def get_update_file_lines(self):
        """
        将需要更新的表转换成一个字典,返回字典
        """
        wb_update_file = load_workbook(self.file_update)
        sheet = wb_update_file.active

        # 创建一个字典  {'bug_id':['']}
        # 获取bug id
        for ii in self.update_column_nums:
            head = sheet.cell(1, ii).value
            self.head.append(head)
        update_bugs = {}
        for i in range(self.update_data_lines):
            bug_id = sheet.cell(i + 2, self.update_bug_id).value
            values = []
            for j in self.update_column_nums:
                values.append(sheet.cell(i + 2, j).value)
            line_value = {bug_id: values}
            update_bugs.update(line_value)
        return update_bugs

    def write_excel(self):
        update_bugs_data = self.get_update_file_lines()
        wb_all_file = load_workbook(self.file_all)
        sheet = wb_all_file.active

        for ii_index, ii_value in enumerate(self.head):
            sheet.cell(1, self.insert_line + self.update_column_nums[ii_index]).value = ii_value
        for i in range(self.all_lines):
            # 获取总表当前行的 bug 号
            bug_id = sheet.cell(i + 2, self.bug_id_column).value
            # 找到bug号后，与更新表bug号匹配，获取更新表内的内容
            try:
                need_update_data = update_bugs_data[bug_id]
            except KeyError:
                continue
            # 将此列表内容插入到新表中
            for index, value in enumerate(need_update_data):
                sheet.cell(i + 2, self.insert_line + index + 1).value = value
        wb_all_file.save(config.FINALL_FILE_PATH)


if __name__ == '__main__':
    add = AddData(config.ALL_DATA_FILE, config.UPDATE_DATA_FILE)
    add.write_excel()
    print("all successful")
